package com.kay.factory;

import com.kay.annote.Autowired;
import com.kay.annote.Service;
import com.kay.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description:
 * @Author: Kay
 * @CreateDate: 2021/7/6$ 13:36$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/7/6$ 13:36$
 */
@Service
public class ProxyFactory {

    @Autowired
    private TransactionManager transactionManager;

//    public void setTransactionManager(TransactionManager transactionManager) {
//        this.transactionManager = transactionManager;
//    }

    public Object getProxyObject(Object object){
        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try {
                    // 开启事务
                    transactionManager.beginTransaction();
                    // 执行原方法
                    result =  method.invoke(object, args);
                    // 提交事务
                    transactionManager.commitTransaction();
                }catch (Exception e){
                    transactionManager.rollBack();
                    // 向上抛出异常
                    throw e;
                }
                return result;
            }
        });
    }
}
